﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunny.UI;
using HYI.SDBSERVER;

namespace SDBSERVER
{
    public partial class FMPOPWINDOW : Form
    {
        public string FieldList ;
        public string QuerySQL;//查询语句
        public string QueryOrder;//排序
        public string SELDATA;//返回当前选择行
        public int SELTYPE=0;//选择方式:单选/多选
        public string sUser;
        public string sMenu;

        DBSERVER myADO = new DBSERVER();
        private int rowindex = -1;
        /// <summary>
        /// 每页记录数
        /// </summary>
        private int pageSize = 15;

        /// <summary>
        /// 总记录数
        /// </summary>
        private int recordCount = 0;

        /// <summary>
        /// 总页数
        /// </summary>
        private int pageCount = 0;

        /// <summary>
        /// 当前页
        /// </summary>
        private int currentPage = 0;

        private DataTable Qrytable = new DataTable();

        /// <summary>
        /// 分页的方法
        /// </summary>
        /// <param name="str"></param>
        private void PageSorter()
        {
            //创建虚拟表
            recordCount = Qrytable.Rows.Count;     //记录总行数
            pageCount = (recordCount / pageSize);
            if ((recordCount % pageSize) > 0)
            {
                pageCount++;
            }

            //默认第一页
            currentPage = 1;

            LoadPage();//调用加载数据的方法
        }

        /// <summary>
        /// LoadPage方法
        /// </summary>
        private void LoadPage()
        {
            if (currentPage < 1) currentPage = 1;
            if (currentPage > pageCount) currentPage = pageCount;

            int beginRecord;    //开始指针
            int endRecord;      //结束指针
            DataTable dtTemp;
            dtTemp = Qrytable.Clone();

            beginRecord = pageSize * (currentPage - 1);
            if (currentPage == 1) beginRecord = 0;
            endRecord = pageSize * currentPage;

            if (currentPage == pageCount) endRecord = recordCount;
            for (int i = beginRecord; i < endRecord; i++)
            {
                dtTemp.ImportRow(Qrytable.Rows[i]);
            }
            uiDGView.Rows.Clear();
            for (int i = 0; i < dtTemp.Rows.Count; i++)
            {
                //dataGridView1.Rows.Add(new object[] { dtTemp.Rows[i][0], dtTemp.Rows[i][1], dtTemp.Rows[i][2] });
                int index = this.uiDGView.Rows.Add();

                if (SELTYPE == 1)
                {
                    this.uiDGView.Rows[index].Cells[0].Value = false;
                }

                for (int j = 0; j < dtTemp.Columns.Count; j++)
                {
                    if (SELTYPE == 0)
                    {
                        this.uiDGView.Rows[index].Cells[j].Value = dtTemp.Rows[i][j];
                    }
                    else
                    {
                        this.uiDGView.Rows[index].Cells[j+1].Value = dtTemp.Rows[i][j];
                    }
                }
            }
            labPageIndex.Text = "" + currentPage.ToString() + "/" + pageCount.ToString();//当前页
            //labRecordCount.Text = "总行数: " + recordCount.ToString() + " 行";//总记录数

            uiDGView.AllowUserToAddRows = false;//關閉dataGridview中最後一個空白行。
        }

        /// <summary>
        /// 首页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFirst_Click(object sender, EventArgs e)
        {
            if (currentPage == 1)
            { return; }
            currentPage = 1;
            LoadPage();
        }
        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrev_Click(object sender, EventArgs e)
        {
            if (currentPage == 1)
            { return; }
            currentPage--;
            LoadPage();
        }
        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNext_Click(object sender, EventArgs e)
        {
            if (currentPage == pageCount)
            { return; }
            currentPage++;
            LoadPage();
        }
        /// <summary>
        /// 尾页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLast_Click(object sender, EventArgs e)
        {
            if (currentPage == pageCount)
            { return; }
            currentPage = pageCount;
            LoadPage();
        }

        /// <summary>
        /// 创建表格列
        /// </summary>
        private void doCreateColumn()
        {
            if (uiDGView.Columns.Count > 0)
            {
                return;
            }

            for (int i = 0; i < Qrytable.Columns.Count; i++)
            {
                string dgvColName = Qrytable.Columns[i].ToString();
                string dgvColHeaderText = Qrytable.Columns[i].ToString();
                Type dataType = Qrytable.Columns[i].DataType;
                //Console.WriteLine(dataType.ToString());
                DataGridViewColumn dgvcolumn = new DataGridViewTextBoxColumn();
                if (dataType.Name == "String")
                {
                    dgvcolumn.ValueType = typeof(string);
                }
                else if (dataType.Name == "Int32")
                {
                    dgvcolumn.ValueType = typeof(int);
                }
                else if (dataType.Name == "DateTime")
                {
                    dgvcolumn.ValueType = typeof(string);
                }
                else
                {
                    dgvcolumn.ValueType = typeof(string);
                }
                dgvcolumn.Name = dgvColName;                        //列名
                dgvcolumn.HeaderText = dgvColHeaderText;  //列头名
                dgvcolumn.ReadOnly = true;
                uiDGView.Columns.Add(dgvcolumn); //增加列
            }

            if (SELTYPE == 1)
            {
                //先建立個 CheckBox 欄
                DataGridViewCheckBoxColumn cbCol = new DataGridViewCheckBoxColumn();
                cbCol.Name = "checkboxHeader";
                cbCol.Width = 80;   //設定寬度
                cbCol.HeaderText = "　  全选";
                cbCol.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;   //置中
                uiDGView.Columns.Insert(0, cbCol);

                #region 建立全选 CheckBox

                //建立個矩形，等下計算 CheckBox 嵌入 GridView 的位置
                Rectangle rect = uiDGView.GetCellDisplayRectangle(0, -1, true);
                rect.X = rect.Location.X + rect.Width / 4 - 9;
                rect.Y = rect.Location.Y + (rect.Height / 2 - 9);

                CheckBox cbHeader = new CheckBox();
                cbHeader.Name = "checkboxHeader";
                cbHeader.Size = new Size(18, 18);
                cbHeader.Location = rect.Location;
                cbHeader.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(80)))), ((int)(((byte)(160)))), ((int)(((byte)(255)))));
                //全選要設定的事件
                cbHeader.CheckedChanged += new EventHandler(cbHeader_CheckedChanged);

                //將 CheckBox 加入到 dataGridView
                uiDGView.Controls.Add(cbHeader);

                #endregion
            }

            //刷新表格中文名称，显示宽度；如果宽度>当前表格宽度 界面放宽
            DBCache myCache = new DBCache();
            myCache.doSetGridVIew(sMenu,sUser, uiDGView);

            int iWidth = 0;
            for (int i = 0; i < uiDGView.Columns.Count; i++)
            {
                iWidth = iWidth + uiDGView.Columns[i].Width;
            }
            if (iWidth > this.Width)
            {
                this.Width = iWidth + 25;
            }


        }

        private void cbHeader_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataGridViewRow dr in uiDGView.Rows)
                dr.Cells[0].Value = ((CheckBox)uiDGView.Controls.Find("checkboxHeader", true)[0]).Checked;
        }

        public FMPOPWINDOW()
        {
            InitializeComponent();
        }

        private void FMPOPWINDOW_Load(object sender, EventArgs e)
        {
            this.btnPrev.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(0)))));
            this.btnNext.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(0)))));

            doLoad();

            pictureBox1.Left = this.Width - 32 - 2;
            pictureBox1.Top = 2;
            pictureBox1.Height = 32;
            pictureBox1.Width = 32;
        }

        //执行查询
        private void doQuery(string SQL)
        {
            Qrytable = myADO.query(SQL);

            if(Qrytable is null)
            {
                UIMessageTip.ShowOk("请重新查询");
                return;
            }

            rowindex = -1;
            doCreateColumn();

            uiDGView.Rows.Clear();
            if (Qrytable is null || Qrytable.Rows.Count == 0)
            {
                Console.WriteLine("0");
                labPageIndex.Text = "0/0";
                btnFirst.Enabled = false;
                btnPrev.Enabled = false;
                btnNext.Enabled = false;
                btnLast.Enabled = false;
                return;
            }

            btnFirst.Enabled = true;
            btnPrev.Enabled = true;
            btnNext.Enabled = true;
            btnLast.Enabled = true;

            PageSorter();//分页 
        }

        //触发查询
        void txt_LostFocus(object sender, EventArgs e)
        {
            //转化一下
            string sWhere = string.Empty;
            foreach (Control ctrl in uiTitle.Controls)
            {
                if (ctrl is UITextBox)
                {
                    if (ctrl.Text != "")
                    {
                        sWhere = sWhere + " and " + ctrl.Tag.ToString()
                            + " like '%" + ctrl.Text + "%'";
                    };
                }
            }

           string SQL= QuerySQL 
                + sWhere
                + QueryOrder;
            Console.WriteLine(SQL);

            doQuery(SQL);

            rowindex = -1;
        }

        private void doLoad()
        {
            int iLeft = 10;
            string[] strArray1 = FieldList.Split(';');
            for (int i = 0; i < strArray1.Length; i++)
            {
                string[] strArray2 = strArray1[i].Split(',');

                UILabel myLab = new UILabel();
                myLab.Tag = "myLab" + i.ToString();
                myLab.Text = strArray2[1];
                myLab.Left = iLeft;
                myLab.Top = 15;
                myLab.Font = new System.Drawing.Font("微软雅黑", 12F);
                //myLab.AutoSize = true;
                myLab.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(235)))), ((int)(((byte)(243)))), ((int)(((byte)(255)))));
                myLab.Parent = uiTitle;

                UITextBox myText = new UITextBox();
                myText.Tag = strArray2[0];
                myText.Left = iLeft;
                myText.Top = 65;
                myText.Width = int.Parse(strArray2[2]);
                myText.Font = new System.Drawing.Font("微软雅黑", 12F);
                //myText.AutoSize = true;

                myText.Leave += new EventHandler(txt_LostFocus); //失去焦点后发生事件
                myText.Parent = uiTitle;

                iLeft = iLeft + int.Parse(strArray2[2]) + 10;

            }

            //设置表格栏位
            doQuery(QuerySQL+QueryOrder);

            //设置整体界面宽度
            Console.WriteLine(iLeft.ToString());

            if (this.Width < iLeft)
            {
                this.Width = iLeft + 30;
            }
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void uiDGView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            rowindex = e.RowIndex;
        }

        private void uiBtn1_Click(object sender, EventArgs e)
        {
            //双击返回
            Console.WriteLine("行:" + rowindex.ToString());
            if (rowindex == -1)
            {
                UIMessageTip.ShowOk("请选择要返回的行");
                return;
            }

            SELDATA = "";
            if (SELTYPE == 0)
            {
                for (int i = 0; i < uiDGView.Columns.Count; i++)
                {
                    SELDATA = SELDATA + uiDGView.Rows[rowindex].Cells[i].Value.ToString() + ",";
                }
            }
            else
            {
                for (int j = 0; j < this.uiDGView.Rows.Count; j++)
                {
                    if ((bool)this.uiDGView.Rows[j].Cells[0].Value)
                    {
                        for (int i = 0; i < uiDGView.Columns.Count - 1; i++)
                        {
                            SELDATA = SELDATA + uiDGView.Rows[j].Cells[i + 1].Value.ToString() + ",";
                        }

                        SELDATA = SELDATA + ";";
                    }
                }
            }
            this.Close();
        }

        private void uiPanel1_DoubleClick(object sender, EventArgs e)
        {
            //Console.WriteLine("当前用户:" + sUser);
            //if (sUser.ToLower() != "888888")
            //{
            //    return;
            //}
            FMSetGridView myGrid = new FMSetGridView();
            myGrid._UserId = sUser;
            myGrid.doLoadGrid(sMenu, uiDGView);
            myGrid.ShowDialog();
            myGrid.Dispose();
            myGrid.Dispose();
        }
    }
}
